<template>
  <div v-loading="loading" class="exam-record-detail">
    <template v-if="recordData">
      <!-- 基本信息 -->
      <div class="info-section">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户">
            {{ recordData.user_id?.username || "未知用户" }}
            <span class="text-gray-500 ml-2">{{
              recordData.user_id?.phone
            }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="考试活动">
            {{ recordData.exam_id?.exam_name || "未知考试" }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ formatDate(recordData.start_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{
              recordData.submit_time
                ? formatDate(recordData.submit_time)
                : "未提交"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="考试状态">
            <el-tag :type="getStatusTagType(recordData.status)">
              {{ getStatusText(recordData.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否超时">
            <el-tag :type="recordData.is_timeout ? 'danger' : 'success'">
              {{ recordData.is_timeout ? "是" : "否" }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 成绩统计 -->
      <div v-if="recordData.status === 'completed'" class="score-section">
        <h3>成绩统计</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic
              title="总得分"
              :value="recordData.user_score || 0"
              suffix="分"
            >
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  总得分
                </div>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="总分"
              :value="recordData.total_score || 0"
              suffix="分"
            />
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="得分率"
              :value="
                getScorePercent(recordData.user_score, recordData.total_score)
              "
              suffix="%"
              :value-style="{
                color: getScorePercentColor(
                  recordData.user_score,
                  recordData.total_score
                ),
              }"
            />
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="用时"
              :value="
                getExamDuration(recordData.start_time, recordData.submit_time)
              "
            />
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="8">
            <el-statistic
              title="正确题数"
              :value="recordData.correct_count || 0"
              suffix="题"
            />
          </el-col>
          <el-col :span="8">
            <el-statistic
              title="错误题数"
              :value="recordData.wrong_count || 0"
              suffix="题"
            />
          </el-col>
          <el-col :span="8">
            <el-statistic
              title="未答题数"
              :value="recordData.unanswered_count || 0"
              suffix="题"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 答题详情 -->
      <div v-if="recordData.answers?.length > 0" class="answers-section">
        <h3>答题详情</h3>
        <el-table :data="recordData.answers" stripe style="width: 100%">
          <el-table-column type="index" label="题号" width="60" />

          <el-table-column label="题目内容" min-width="300">
            <template #default="{ row }">
              <div class="question-content">
                <div class="question-text">
                  {{ row.question_snapshot?.content || "题目内容缺失" }}
                </div>
                <div
                  v-if="
                    row.question_snapshot?.type === 'multiple_choice' &&
                    row.question_snapshot?.options
                  "
                  class="question-options"
                >
                  <div
                    v-for="(option, index) in row.question_snapshot.options"
                    :key="index"
                    class="option-item"
                    :class="{
                      'correct-option':
                        row.question_snapshot.correct_answer?.includes(index),
                      'selected-option': row.selected_answers?.includes(index),
                      'wrong-selected':
                        row.selected_answers?.includes(index) &&
                        !row.question_snapshot.correct_answer?.includes(index),
                    }"
                  >
                    <span class="option-symbol">{{ option.symbol }}.</span>
                    <span class="option-content">{{ option.content }}</span>
                    <span
                      v-if="
                        row.question_snapshot.correct_answer?.includes(index)
                      "
                      class="correct-mark"
                      >✓</span
                    >
                    <span
                      v-if="row.selected_answers?.includes(index)"
                      class="selected-mark"
                    >
                      {{
                        row.question_snapshot.correct_answer?.includes(index)
                          ? "✓"
                          : "✗"
                      }}
                    </span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="题目类型" width="100">
            <template #default="{ row }">
              {{ getQuestionTypeText(row.question_snapshot?.type) }}
            </template>
          </el-table-column>

          <el-table-column label="用户答案" width="120">
            <template #default="{ row }">
              <template v-if="row.selected_answers?.length > 0">
                <el-tag
                  v-for="(answerIndex, index) in row.selected_answers"
                  :key="index"
                  size="small"
                  :type="
                    row.question_snapshot?.correct_answer?.includes(answerIndex)
                      ? 'success'
                      : 'danger'
                  "
                  style="margin: 2px"
                >
                  {{ getOptionSymbol(answerIndex) }}
                </el-tag>
              </template>
              <template v-else>
                <el-tag type="info" size="small">未作答</el-tag>
              </template>
            </template>
          </el-table-column>

          <el-table-column label="正确答案" width="120">
            <template #default="{ row }">
              <el-tag
                v-for="(answerIndex, index) in row.question_snapshot
                  ?.correct_answer || []"
                :key="index"
                size="small"
                type="success"
                style="margin: 2px"
              >
                {{ getOptionSymbol(answerIndex) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="是否正确" width="100">
            <template #default="{ row }">
              <el-tag
                :type="row.is_correct ? 'success' : 'danger'"
                size="small"
              >
                {{ row.is_correct ? "正确" : "错误" }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="得分" width="80">
            <template #default="{ row }">
              <span class="score-text">
                {{ row.earned_score || 0 }} /
                {{ row.question_snapshot?.score || 0 }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>

    <div v-else-if="!loading" class="no-data">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  ref,
} from 'vue';

import { ElMessage } from 'element-plus';

import type { IExamRecord } from '@shared/types/exam';

import { examRecordApi } from '../../../api/modules/examRecord.api';

interface Props {
  recordId: string;
}

const props = defineProps<Props>();

// 响应式数据
const loading = ref(false);
const recordData = ref<IExamRecord | null>(null);

// 生命周期
onMounted(() => {
  loadRecordDetail();
});

// 加载考试记录详情
const loadRecordDetail = async () => {
  try {
    loading.value = true;
    const response = await examRecordApi.getExamRecordDetail(props.recordId);
    if (response.data?.code === 200) {
      recordData.value = response.data.data;
    } else {
      ElMessage.error("获取考试记录详情失败");
    }
  } catch (error) {
    console.error("获取考试记录详情失败:", error);
    ElMessage.error("获取考试记录详情失败");
  } finally {
    loading.value = false;
  }
};

// 辅助函数
const formatDate = (date: string | Date) => {
  if (!date) return "--";
  const d = new Date(date);
  if (isNaN(d.getTime())) return "--";

  return d.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    in_progress: "进行中",
    completed: "已完成",
    timeout: "已超时",
  };
  return statusMap[status] || "未知状态";
};

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    in_progress: "warning",
    completed: "success",
    timeout: "danger",
  };
  return typeMap[status] || "info";
};

const getScorePercent = (score: number, total: number) => {
  if (!total || total === 0) return 0;
  return Math.round((score / total) * 100);
};

const getScorePercentColor = (score: number, total: number) => {
  const percent = getScorePercent(score, total);
  if (percent >= 90) return "#67c23a";
  if (percent >= 80) return "#e6a23c";
  if (percent >= 60) return "#f56c6c";
  return "#909399";
};

const getExamDuration = (startTime: string | Date, endTime: string | Date) => {
  if (!startTime || !endTime) return "--";

  const start = new Date(startTime);
  const end = new Date(endTime);
  const duration = end.getTime() - start.getTime();

  const minutes = Math.floor(duration / (1000 * 60));
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;

  if (hours > 0) {
    return `${hours}小时${remainingMinutes}分钟`;
  }
  return `${remainingMinutes}分钟`;
};

const getQuestionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    single_choice: "单选题",
    multiple_choice: "多选题",
    true_false: "判断题",
    fill_blank: "填空题",
    essay: "问答题",
  };
  return typeMap[type] || "未知类型";
};

const getOptionSymbol = (index: number) => {
  return String.fromCharCode(65 + index); // A, B, C, D...
};
</script>

<style scoped>
.exam-record-detail {
  padding: 20px 0;
}

.info-section,
.score-section,
.answers-section {
  margin-bottom: 30px;
}

.info-section h3,
.score-section h3,
.answers-section h3 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.question-content {
  line-height: 1.6;
}

.question-text {
  font-weight: 500;
  margin-bottom: 10px;
  color: #303133;
}

.question-options {
  margin-top: 8px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  margin: 2px 0;
  border-radius: 4px;
  position: relative;
}

.option-item.correct-option {
  background-color: #f0f9ff;
  border: 1px solid #67c23a;
}

.option-item.selected-option {
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
}

.option-item.selected-option.correct-option {
  background-color: #f0f9ff;
  border: 1px solid #67c23a;
}

.option-symbol {
  font-weight: 600;
  margin-right: 8px;
  min-width: 20px;
}

.option-content {
  flex: 1;
}

.correct-mark,
.selected-mark {
  margin-left: 8px;
  font-weight: 600;
}

.correct-mark {
  color: #67c23a;
}

.selected-mark {
  color: #f56c6c;
}

.option-item.correct-option .selected-mark {
  color: #67c23a;
}

.score-text {
  font-weight: 600;
  color: #409eff;
}

.text-gray-500 {
  color: #909399;
}

.ml-2 {
  margin-left: 8px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
